/*
 * @Author: wei_jt@ecidi.com
 * @Date: 2020-04-29 09:54:06
 * @LastEditors: wei_jt@ecidi.com
 * @LastEditTime: 2022-04-14 15:44:25
 * @Description: 封装 storage类
 */
import Vue from 'vue'
import { appName, storageInMainApp } from '@/config'

if (process.env.NODE_ENV == 'development') {
  sessionStorage.setItem('storageIsolation', '0')
}

/**
 * @description: 获得缓存的前缀
 *               默认为 appName_，开启隔离后变为 NODE_ENV_appName_
 *               子应用中，特殊参数直接使用主应用的前缀，这样能取到主应用缓存的数据
 *               
 */
export function getStoragePrefix (name = '') {
  if (Vue.prototype.$InQianKun && storageInMainApp.includes(name)) {
    if (Vue.prototype.$fksMainFunc.getStoragePrefix) {
      return Vue.prototype.$fksMainFunc.getStoragePrefix()
    }
  }

  let IsolationPrefix = sessionStorage.getItem('storageIsolation') ? '' : `${process.env.NODE_ENV}_`
  return `${IsolationPrefix}${appName}_`
}

export default {
  /**
 * @description: localStorage存储封装
 * @param {String} name
 * @param {String} value
 * @return: void
 */
  set: (name, value) => {
    localStorage.setItem(`${getStoragePrefix(name)}${name}`, value)
  },

  /**
   * @description: localStorage获取封装
   * @param {String} name
   * @return: String
   */
  get: (name) => {
    return localStorage.getItem(`${getStoragePrefix(name)}${name}`)
  },

  /**
   * @description: localStorage移除封装
   * @param {String} name
   * @return: void
   */
  remove: (name) => {
    localStorage.removeItem(`${getStoragePrefix(name)}${name}`)
  },

  /**
   * @description: localStorage清空封装
   * @param {String} name
   * @return: String
   */
  clear: () => {
    let len = localStorage.length
    let keys = []

    for (let i = 0; i < len; i++) {
      let key = localStorage.key(i)
      if (key && key.startsWith(getStoragePrefix())) {
        keys.push(key)
      }
    }

    keys.map(key => localStorage.removeItem(key))
  }
}